package com.yyy.util;

import com.yyy.gui.pannel.WorkingPanel;

import javax.swing.*;
import java.awt.*;

/**
 * @Author：yyy
 * @Package：com.yyy.util
 * @Project：HuTuBiill
 * @name：CenterPanel
 * @Date：2024/11/7 22:35
 * @Filename：CenterPanel
 */
public class CenterPanel extends JPanel {
    private double rate;  //拉伸比例，1就是填满，0.5就是填充一半
    private JComponent c; //显示的组件
    private boolean strech;//是否拉伸
    //构造方法
    public CenterPanel(double rate,boolean strech){
        this.setLayout(null);
        this.rate=rate;
        this.strech=strech;
    }
    public CenterPanel(double rate){
        this(rate,true);
    }

    //显示组件
    public void show(JComponent p){
        this.c=p;
        Component[] cs=getComponents();
        for(Component c:cs){
            remove(c);
        }
        add(p);
        if(p instanceof WorkingPanel)
            ((WorkingPanel)p).updateData();//更新界面数据
        this.updateUI();//通过这个方法会导致swing调用repaint()方法

    }

    public void repaint(){
        if(c!=null){
            Dimension containerSize=this.getSize();
            Dimension componentSize=c.getPreferredSize();
            if(strech){
                c.setSize((int)(containerSize.width*rate),(int)(containerSize.height*rate));
            }else {
                c.setSize(componentSize);
            }
            c.setLocation(containerSize.width/2-c.getSize().width/2,containerSize.height/2-c.getSize().height/2);
        }
        super.repaint();
    }

    public static void main(String[] args) {
        JFrame f=new JFrame();
        f.setSize(200,200);
        f.setLocationRelativeTo(null);
        CenterPanel cp=new CenterPanel(0.5,true);
        f.setContentPane(cp);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        JButton button=new JButton("ABC");
        cp.show(button);
    }




}
